package org.openmrs.propertyeditor;

import java.beans.PropertyEditorSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.ObligationContext;
import org.openmrs.api.UserService;
import org.openmrs.api.context.Context;
import org.springframework.util.StringUtils;

public class ObligationContextEditor extends PropertyEditorSupport {
	
	private Log log = LogFactory.getLog(this.getClass());
	
	public ObligationContextEditor() {
		
	}
	
	/**
	 * @should set using name
	 * @should set using uuid
	 */
	public void setAsText(String text) throws IllegalArgumentException {
		UserService es = Context.getUserService();
		if (StringUtils.hasText(text)) {
			try {
				ObligationContext r = es.getObligationContextById(text);
				setValue(r);
				//when a role is not found, no exception is generated. throw one to execute the catch block
				if (r == null)
					throw new Exception();
			}
			catch (Exception ex) {

			}
		} else {
			setValue(null);
		}
	}
	
	public String getAsText() {
		ObligationContext context = (ObligationContext) getValue();
		if (context == null)
			return "";
		else
			return context.getContextName();
	}
	
}
